package com.mDigitalHealth.thread;

import java.util.Calendar;

import com.mDigitalHealth.common.Utils;
import com.mDigitalHealth.database.DataType;
import com.mDigitalHealth.database.DatabaseHelper;
import com.mDigitalHealth.database.Store;
import com.mDigitalHealth.network.DigitalHealthClient;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class UploadThread extends Thread {

	Context context;
	SharedPreferences statePreference;
	SharedPreferences.Editor stateEditor;
	public UploadThread(Context context, SharedPreferences statePreference, SharedPreferences.Editor stateEditor){
		this.context = context;
		this.statePreference = statePreference;
		this.stateEditor = stateEditor;
		System.out.println("***upload thead construct");
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		
		SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		String name = mSharedPreferences.getString(Utils.PREFERENCE_KEY_USER_NAME, "");
		Calendar mCalendar = Calendar.getInstance();
		mCalendar.set(Calendar.MINUTE, 0);
		DatabaseHelper mDatabaseHelper = new DatabaseHelper(context);
		ContentValues values = new ContentValues();
		values.put(Store.DailyDataColumns.DAY_STAMP, mCalendar.getTimeInMillis());
		values.put(Store.DailyDataColumns.DAY_STEP_COUNT_TOTAL, statePreference.getInt("steps", 0));
		values.put(Store.DailyDataColumns.LOGIN_NAME, name);
		values.put(Store.DailyDataColumns.DAY_STEP_COUNT_HIGH, 0);
		values.put(Store.DailyDataColumns.DAY_STEP_COUNT_MID, statePreference.getInt("steps", 0));
		values.put(Store.DailyDataColumns.DAY_STEP_COUNT_LOW, 0);
		mDatabaseHelper.insert(DataType.DAILY_DATA, values);
		
		stateEditor.putInt("steps", 0);
//		stateEditor.putInt("pace", 0);
		stateEditor.putFloat("distance", 0);
//		stateEditor.putFloat("speed", 0);
		stateEditor.putFloat("calories", 0);
		stateEditor.commit();
		
		Intent intent = new Intent(Utils.BROADCAST_ACTION_RESET_VALUES);
		context.sendBroadcast(intent);
		
		DigitalHealthClient.uploadUserHourStepInfo(context, name);
		
		long time = mCalendar.getTimeInMillis() - 3600 * 1000 * 24 * 7 - 3600 * 1000;
		mDatabaseHelper.delete(DataType.HOUR_DATA, Store.HourDataColumns.HOUR_STAMP + " < ?  AND "+Store.HourDataColumns.LOGIN_USER + " = ? ", new String[]{String.valueOf(time),name});
		mDatabaseHelper.delete(DataType.DAILY_DATA, Store.DailyDataColumns.DAY_STAMP + " < ?  AND "+Store.DailyDataColumns.LOGIN_NAME + " = ? ", new String[]{String.valueOf(time),name});
		mDatabaseHelper.close();
		mDatabaseHelper = null;
		
	}

	
}
